import { observable, action, toJS } from 'mobx';
import * as Detail from '../apis/detail';
import { message, Modal } from 'antd';

const { confirm } = Modal;
import { WeaTableNew } from 'comsMobx';

const { TableStore } = WeaTableNew;
import { WeaTools } from 'ecCom';

const { watermark } = WeaTools;

class DetailStore {
  @observable loading= false;
  @observable hideContent= false;
  @observable attachHideContent= false;
  @observable replyLoading= false;
  @observable basicInfo = {};
  @observable readCount= '';
  @observable praiseInfo= {};
  @observable rightMenus= [];
  @observable tabInfo= [];
  @observable tabKey= 'content';
  @observable dataKeys= {};
  @observable attrDatas= [];
  @observable scoreDatas= [];
  @observable replyList= [];
  @observable markInfo= {};
  @observable replyCount= 0;
  @observable topSet= {};
  @observable conditions= [];
  @observable shareAddEditBtn= {};
  @observable docAutoExtendInfo= {};
  @observable shareVisible = false;
  constructor() {
    this.basicInfo = {
      docSubject: window.__docsubject || '',
    };
  }

  /**
   * 列表信息
   * */
  @observable fileVersionTableStore = new TableStore();// 文件版本
  @observable markDetailTableStore = new TableStore();// 打分详情
  @observable shareTableStore = new TableStore();// 文档共享
  @observable accTableStore = new TableStore();// 附件
  @observable versionTableStore = new TableStore();// 文件版本
  @observable docIsCheckOut= false; // 判断当前文档是否被迁出
  @observable docCheckOutMsg= ''; // 文档被迁出的提示语

  @observable excludeImgId = ''; // 要被排除的imgid（逗号隔开的形式）
  @observable moudleIds= []; // 逗号隔开的moudleid转化为数组存放
  @observable secWmSet= {}; // 当前文档所在目录的水印展示设置

  @observable docWater={
    isopen: '0',
    view: '0',
    download: '0',
    print: '0',
  };
  @observable isdownload='0';
  @observable mainImagefile = '';
  @action
  getBasic = (params = {}) => {
    this.loading = true;
    Detail.getBasic(params).then(action((data) => {
      this.basicInfo = data.data || {};
      this.rightMenus = data.rightMenus;
      this.loading = false;
      this.secWmSet = data.secWmSet;
      this.setMainImagefile(data.mainimagefile);
      if (data.secWmSet.isopenwater !== '1' || data.secWmSet.wmforview !== '1') {
        setTimeout(() => {
          watermark.destory();
        }, 200);
      }
    }));
    Detail.addReadLog(params)
      .then(action(() => Detail.getReadCount(params)))
      .then(action((data) => {
        this.readCount = data.readCount;
      }));
    Detail.getPraise(params).then(action((data) => {
      this.praiseInfo = data.praiseInfo;
    }));
    Detail.getTabInfo(params).then(action((data) => {
      this.tabInfo = data.tabInfo;
    }));
    Detail.getReplyCount(params).then(action((data) => {
      this.replyCount = data.replyCount;
    }));
    this.docIsCheckOut = false;
    this.docCheckOutMsg = '';
  };

  // 文档详情 文档属性
  @action
  getAttr = (params = {}) => {
    this.loading = true;
    Detail.getAttr(params).then((data) => {
      this.attrDatas = data.data;
      this.loading = false;
      let waterinfo = data.waterinfo;
      waterinfo && Object.keys(waterinfo).forEach((key) => {
        this.docWater[key] = waterinfo[key];
      });
    });
  };
  @action
  setMainImagefile = (val) => {
    this.mainImagefile = val;
  }
  // 文档详情 文档打分
  @action
  getScore = (params = {}) => {
    this.loading = true;
    Detail.getScore(params).then(action((data) => {
      this.scoreDatas = data.docMark;
      this.markInfo = data.markInfo;
      this.loading = false;
    }));
  };

  // 文档详情 文档打分
  @action
  doMark = (params = {}) => {
    this.loading = true;
    Detail.doMark(params).then(action((data) => {
      this.scoreDatas = data.docMark;
      this.markInfo = data.markInfo;
      this.loading = false;
    }));
  };

  // 文档详情 文档点赞
  @action
  setPraise = (params = {}, i = false) => {
    this.loading = true;
    Detail.setPraise(params, i).then(action((data) => {
      if (data.status === 1 && !params.type) {
        this.praiseInfo = { ...this.praiseInfo, isPraised: i ? '1' : '0' };
        this.loading = false;
      }
      if (data.status === 1 && params.type) {
        this.getReplyList({ docid: params.docid });
        this.loading = false;
      }
    }));
  };

  // 更新点赞星信息
  @action
  updateMarkInfo = (params) => {
    this.markInfo = { ...this.markInfo, ...params };
  };

  // 文档详情 获取回复列表
  @action
  getReplyList = (params = {}) => {
    this.replyLoading = true;
    Detail.getReplyList(params).then(action((data) => {
      this.replyList = data.replyList;
      this.replyLoading = false;
    }));
  };

  // 文档详情 回复提交
  @action
  saveReply = (params = {}, hasMore = false) => {
    this.replyLoading = true;
    let replyList = toJS(this.replyList);
    Detail.saveReply(params).then(action((data) => {
      if (data.status === 1) {
        if (params.operate === 'edit') {
          this.replyList = replyList.map(item => (item.replyid === params.replyid ? { ...item, content: params.content } : item));
          this.replyLoading = false;
        } else if (hasMore) {
            const { docid } = params;
            this.getMoreReplyChild({ docid, ...hasMore });
          } else {
            params.replyid ? replyList.push(data.reply) : replyList.unshift(data.reply);
            this.replyList = replyList;
            this.replyLoading = false;
          }
      } else {
        message.warn(data.msg);
        this.replyLoading = false;
      }
    }));
  };

  // 文档详情 获取更多
  @action
  getMoreReplyMain = (params = {}) => {
    this.replyLoading = true;
    Detail.getMoreReplyMain(params).then(action((data) => {
      const replyList = toJS(this.replyList);
      this.replyList = replyList.concat(data.replyList);
      this.replyLoading = false;
    }));
  };

  @action
  getMoreReplyChild = (params = {}) => {
    this.replyLoading = true;
    Detail.getMoreReplyChild(params).then(action((data) => {
      const replyList = toJS(this.replyList);
      this.replyList = replyList.concat(data.replyList);
      this.replyLoading = false;
    }));
  };

  @action
  deleteReply = (params = {}) => {
    this.replyLoading = true;
    const replyList = toJS(this.replyList);
    Detail.deleteReply(params).then(action((data) => {
      if (data.status !== 1) {
        message.warn(data.msg);
      } else {
        this.replyList = data.status === 1
          ? replyList.filter(item => item.replyid !== params.replyid) : replyList;
      }
      this.replyLoading = false;
    }));
  };

  // 文档详情 删除文档
  @action
  deleteWarm = (params = {}) => {
    this.loading = true;
    this.hideContent = true;
    Detail.deleteWarm({}).then((data) => {
      this.loading = false;
      confirm(
        {
          content: (
            <span>
            {data.title}
              {
                data.subTitle ? <span style={{ color: 'red' }}>({data.subTitle})</span> : null
              }
          </span>),
          onOk: () => {
            this.loading = true;
            this.hideContent = false;
            Detail.deleteDoc(params).then(action((datas) => {
              this.loading = false;
              message.success(datas.msg);
              if (datas.status === 1) {
                setTimeout(() => window.close(), 1500);
              }
            }));
          },
          onCancel: () => {
            this.hideContent = false;
          },
        },
      );
    });
  };
  // 设置详情的隐藏
  @action
  setHideContent = (hideContent) => {
    this.hideContent = hideContent;
  }
  // 设置附件的附件编辑插件隐藏
  @action
  setAttachHideContent = (attachHideContent) => {
    this.attachHideContent = attachHideContent;
  }

  // 文档详情 失效
  @action
  invalidate = (params = {}) => {
    this.loading = true;
    Detail.invalidate(params).then(action((data) => {
      this.loading = false;
      if (data.status === 1) {
        message.success(data.msg);
        setTimeout(() => window.location.reload(), 1500);
      } else if (data.status === -1) {
        message.warn(data.msg);
      }
    }));
  };

  // 文档详情  发布
  @action
  publishDoc = (params = {}) => {
    this.loading = true;
    Detail.publishDoc(params).then(action((data) => {
      this.loading = false;
      if (data.status === 1) {
        message.success(data.msg);
        setTimeout(() => window.location.reload(), 1500);
      } else if (data.status === -1) {
        message.warn(data.msg);
      }
    }));
  };

  // 文档详情 获取置顶信息
  @action
  getTopSet = (params = {}) => {
    this.loading = true;
    Detail.getTopSet(params).then(action((data) => {
      this.topSet = data;
      this.loading = false;
    }));
  };

  @action
  updateTopSet = (params) => {
    this.topSet = { ...this.topSet, ...params };
  }

  // 文档详情 设置置顶信息
  @action
  setTop = (params = {}) => {
    this.loading = true;
    Detail.setTop(params).then(action((data) => {
      if (data.status === 1) {
        message.success(data.msg);
        const { docid } = params;
        Detail.getBasic({ docid }).then((d) => {
          this.basicInfo = d.data || {};
          this.rightMenus = d.rightMenus;
          this.loading = false;
        });
      }
    }));
  };

  // 获取共享条件
  @action
  getAddShare = (params = {}) => {
    Detail.getAddShare(params).then(action((data) => {
      this.conditions = data.conditions;
    }));
  };

  // 获取共享条件
  @action
  doShareAddSubmit = (params = {}) => {
    if (params.objType == 2 && params.subcompany != undefined && params.subcompanyspan != undefined) {
      params.obj_id = params.subcompany;
      params.obj_idspan = params.subcompanyspan;
    }
    if (params.objType == 3 && params.department != undefined && params.departmentspan != undefined) {
      params.obj_id = params.department;
      params.obj_idspan = params.departmentspan;
    }
    Detail.doShareAddSubmit(params).then(action((data) => {
      data.status === 1 &&
      this.searchShare({ id: params.id });
    }));
  };

  // 获取共享条件
  @action
  canShareAddEdit = (params = {}) => {
    Detail.canShareAddEdit(params).then(action((data) => {
      this.shareAddEditBtn = data;
    }));
  };

  // 删除共享条件
  @action
  deleteShare = (params = {}) => {
    Detail.deleteShare(params).then(action((data) => {
      data.status === 1
        ? this.searchShare({ id: params.docid })
        : message.warning(data.msg);
    }));
  };

  // 修改共享条件确认
  @action
  afterShareSave = (params = {}) => {
    Detail.afterShareSave(params).then(action((data) => {
      if (data.status === 1) window.location.href = data.link;
    }));
  };

  // 修改共享条件确认
  @action
  convertFile = (params = {}) => {
    Detail.convertFile(params).then(action((data) => { window.afterConvertFile(data); }));
  };

  // 草稿提交
  @action
  draftSubmit = (params = {}, callback) => {
    Detail.draftSubmit(params).then(action((data) => { callback(data); }));
  };

  // 替换文件
  @action
  docAccReplace = (params = {}) => {
    this.loading = true;
    Detail.docAccReplace(params).then(action((data) => {
      this.loading = false;
      if (data.url) window.location.reload();
    }));
  };

  // 正文获取附件列表
  @action
  doDocAutoExtendInfo = (params = {}, moudleParams = '') => {
    Detail.docAutoExtendInfo(params, moudleParams).then(action((data) => {
      this.docAutoExtendInfo = data;
    }));
  }

  @action
  reOpen = (params = {}) => {
    Detail.reOpen(params).then(action((data) => {
      window.location.reload();
    }));
  }
  @action
  reLoad = (params = {}) => {
    Detail.reLoad(params).then(action((data) => {
      window.location.reload();
    }));
  }

  @action
  setTabKey = (tabKey = 0) => {
    this.tabKey = tabKey;
  };

  @action
  searchFileVersion = (params) => {
    this.loading = true;
    Detail.getFileVersion(params).then(action((result) => {
      this.fileVersionTableStore.getDatas(result.sessionkey, params.current || 1);
      this.loading = false;
    }));
  }

  @action
  searchMarkDetail = (params) => {
    this.loading = true;
    Detail.getMarkDetail(params).then(action((result) => {
      this.markDetailTableStore.getDatas(result.sessionkey, params.current || 1);
      this.loading = false;
    }));
  }

  @action
  searchShare = (params) => {
    this.loading = true;
    Detail.getShareTable(params).then(action((result) => {
      this.shareTableStore.getDatas(result.sessionkey, params.current || 1);
      this.loading = false;
    }));
  }

  @action
  searchAcc = (params) => {
    this.loading = true;
    Detail.getAccTable(params).then(action((result) => {
      this.accTableStore.getDatas(result.sessionkey, params.current || 1);
      this.loading = false;
      this.isdownload = result.bacthDownload;
    }));
  }

  @action
  searchVersionTable = (params) => {
    this.loading = true;
    Detail.getVersionTable(params).then(action((result) => {
      this.versionTableStore.getDatas(result.sessionkey, params.current || 1);
      this.loading = false;
    }));
  }

  // 当点击编辑文档的时候，判断当前文档是否有人正在编辑
  @action
  docfileisCheckOut = ({ docid, resource, params }) => {
    Detail.docfileisCheckOut({ id: docid }).then(action((result) => {
      if (resource === 'detail') {
        if (result.api_status === 0) {
          confirm({
            content: result.msg,
            onOk: () => {
              this.setAttachHideContent(false);
            },
            onCancel: () => {
              this.setAttachHideContent(false);
            },
          });
        } else {
          this.setAttachHideContent(false);
          window.location.href =
            `/spa/document/index.jsp?id=${docid}&isEdit=1${window.__moudleParams}#/main/document/edit`;
        }
      } else if (resource === 'attach') {
          if (result.api_status === 0) {
            confirm({
              content: result.msg,
              onOk: () => {
                this.setAttachHideContent(false);
              },
              onCancel: () => {
                this.setAttachHideContent(false);
              },
            });
          } else {
            this.setAttachHideContent(false);
            window.location.href = `/spa/document/index2file.jsp?${params}${window.__moudleParams}#/main/document/fileView`;
          }
      }
    }));
  }
}

export default DetailStore;
